﻿using Domain.Event;
using Domain.IRepositorys;
using Domain.Model;
using Domain.Types;
using Infrastructure.Error;
using Infrastructure.UniOfWorkBase;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static Utility.PolicyUtil;

namespace Domain.Services
{
    public class PayService
    {
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public IUserRepository userRepository { get; set; }
        public IWalletRepository walletRepository { get; set; }
        public IInComeWalletLogRepository walletLogRepository { get; set; }
        public IChargeWalletLogRepository chargeWalletLogRepository { get; set; }
        public IPayCallBackLogRepository PayCallBackLogRepository { get; set; }
        public WalletService walletService { get; set; }
        public MsgPulishService msgPulishService { get; set; }
        public bool PayHandle(CapitalFlowAggregate c)
        {
            var log = PayCallBackLogRepository.Entities.FirstOrDefault(i => i.InstitutionNO == c.InstitutionNO);
            log.IsHandle = true;

            if (c.InstitutionTradeSuccess)//支付成功
            {
                var wallet = walletRepository.Entities.FirstOrDefault(i => i.UserID == c.UserID);

                walletService.ChangeChargeWallet(c.UserID, c.PayMoney, 0, c.SerialNO, FinancialBizType.用户充值, c.BizDesc, c.BizDesc, null,c.ID.ToString(),c.InstitutionTradeSuccess);

                c.IsHandle = true;

                switch (c.BizType)
                {
                    case Types.CapitalFlowBizType.用户充值:
                        {
                            c.HandleInfo = "用户充值，更新余额";
                            break;
                        }
                    //case CapitalFlowBizType.支付任务:
                    //    {
                    //        c.HandleInfo = "用户充值，更新余额";

                    //        //[{"TaskID":"1"},{"TaskAudit":"1"}]
                    //        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(c.BizParams);

                    //        wallet.AddDomainEvent(new PayTaskEvent()
                    //        {
                    //            UserID = c.UserID,
                    //            TaskID = int.Parse(dic["TaskID"]),
                    //            TaskAuditID = int.Parse(dic["TaskAuditID"]),
                    //            CT = DateTime.Now
                    //        });
                    //        break;
                    //    }
                    //case CapitalFlowBizType.支付超级商人升级:
                    //    {
                    //        c.HandleInfo = "用户充值，更新余额";
                    //        //[{"Month":"1"}]
                    //        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(c.BizParams);

                    //        wallet.AddDomainEvent(new PayUpLevelByTraderEvent()
                    //        {
                    //            UserID = c.UserID,
                    //            Month = int.Parse(dic["Month"]),
                    //            CT = DateTime.Now,
                    //            PayID = c.ID,
                    //            PayMoney = c.PayMoney
                    //        });
                    //        break;
                    //    }
                    //case CapitalFlowBizType.支付道具:
                    //    {
                    //        c.HandleInfo = "用户充值，更新余额";
                    //        //支付道具 参数:[{"PropType":"","Num":""}]刷新=0  数量
                    //        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(c.BizParams);

                    //        wallet.AddDomainEvent(new PayUserPropEvent()
                    //        {
                    //            UserID = c.UserID,
                    //            PropType = (PropType)int.Parse(dic["PropType"]),
                    //            CT = DateTime.Now,
                    //            Num = int.Parse(dic["Num"])
                    //        });
                    //        break;
                    //    }
                    //case CapitalFlowBizType.支付推荐:
                    //    {
                    //        c.HandleInfo = "用户充值，更新余额";
                    //        //支付道具 参数:[{"PropType":"","Num":""}]刷新=0  数量
                    //        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(c.BizParams);

                    //        wallet.AddDomainEvent(new PayRecommendEvent()
                    //        {
                    //            UserID = c.UserID,
                    //            CT = DateTime.Now,
                    //            Hour = int.Parse(dic["Hour"]),
                    //            TaskID = int.Parse(dic["TaskID"])
                    //        });
                    //        break;
                    //    }
                    default:
                        throw new BizException("未知业务类型无法处理");
                }

                try
                {
                    log.HandleInfo = "处理完成";
                    efUnitOfWork.Commit();
                    if (c.BizType==CapitalFlowBizType.用户充值) msgPulishService.SendMsg(c.UserID, "冲值成功", $"冲值{((double)c.PayMoney) / 100}成功!");
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    log.IsError = true;
                    log.HandleInfo = ex.Message;
                    efUnitOfWork.Rollback();
                    throw new PolicyRetryException();
                }

                return true;
            }
            else //支付失败
            {
                c.IsHandle = true;
                c.HandleInfo = "用户充值支付失败";

                log.IsError = true;
                log.HandleInfo = "用户充值支付失败";

                efUnitOfWork.Commit();

                return true;
            }
        }

        public bool ChargeMarginBlance(int uid, int money)
        {
            var wallet = walletRepository.Entities.FirstOrDefault(i => i.UserID == uid);

            if (wallet.ChargeBlance < money) throw new BizException("用户钱包余额不足");

            walletService.ChangeChargeWallet(uid, -money, money, null
                , FinancialBizType.冲值保证金, FinancialBizType.冲值保证金.ToString(),
                $"{FinancialBizType.冲值保证金.ToString()}  当前:{wallet.MarginBlance} 增加:{money}");

            //记录
            wallet.MarginBlance += money;

            try
            {
                return efUnitOfWork.Commit() > 0;
            }
            catch (DbUpdateConcurrencyException ex)
            {
                efUnitOfWork.Rollback();
                throw new BizException("系统繁忙,请稍后重试!");
            }

        }
    }
}
